/**
 * 
 */
package os.filesystem.storage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import os.filesystem.file.File;

/**
 * 
 * @author Raghav Sidhanti
 * @since Mar 6, 2012 11:47:08 AM
 * 
 */
public class DiskIO implements IO {

	private String diskLocation;

	/**
	 * Default constructor.
	 */
	public DiskIO(String diskLocation) {
		this.diskLocation = diskLocation;
	}

	private Object storage = new Object();

	/*
	 * (non-Javadoc)
	 * 
	 * @see os.filesystem.storage.IO#write(os.filesystem.file.File)
	 */
	public void write(File f) {
		synchronized (storage) {
			try {
				FileOutputStream fos = new FileOutputStream(diskLocation + "/" + f.getMeta().getAbsoluteName());
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				oos.writeObject(f);
				oos.close();

			} catch (IOException e) {
				System.err.println(e);
				// TODO Add Logger
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see os.filesystem.storage.IO#open(java.lang.String)
	 */
	public File read(String filename) throws IOException, ClassNotFoundException {
		synchronized (storage) {
				FileInputStream fis = new FileInputStream(diskLocation + "/" + filename);
				ObjectInputStream ois = new ObjectInputStream(fis);
				File f = (File) ois.readObject();
				ois.close();
				return f;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see os.filesystem.storage.IO#delete(java.lang.String)
	 */
	public void delete(String f) throws FileNotFoundException {
		synchronized (storage) {
			java.io.File file = new java.io.File(diskLocation + "/" + f);
			if(file.exists()){
				file.delete();
			}else{
				throw new FileNotFoundException("Missing file on disk: " + f);
			}

		}
	}

}
